package cn.zx.rmq.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.io.UnsupportedEncodingException;

/**
 * @Package: cn.zx.rmq.producer
 * @ClassName: SyncProducer
 * @Author: Think
 * @CreateTime: 2021/6/28 10:58
 * @Description: 同步发送消息示例，所有消息同步按照顺序发送，只有上一条消息完成发送并获得反馈结果后，才开始下一条消息的发送。
 * 同一个线程同步阻塞式地进行消息的发送，比较适合需要根据上一次发送结果来做逻辑判断，以决定下一次是否发送的场景。
 */
@Slf4j
public class SyncProducer {

    public static void main(String[] args) throws MQClientException, MQBrokerException, RemotingException, InterruptedException, UnsupportedEncodingException {
        DefaultMQProducer producer = new DefaultMQProducer("SyncProducer-Group");
        producer.setNamesrvAddr("localhost:9876");
        producer.start();

        for (int i = 0; i < 5; i++) {
            Message msg = new Message("KYC", "about-money", ("客户拥有金额为：" + i*1000).getBytes(RemotingHelper.DEFAULT_CHARSET));
            SendResult sendResult = producer.send(msg);
            log.info("发送返回信息为：{}", sendResult);
        }

        producer.shutdown();
    }

}
